package com.ming.springboot.security;

import com.ming.springboot.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权格式(http header): Authorization:Bearer <token>
 * Created by mqsi on 2022/5/24 21:08
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
	@Autowired
	SelfUserDetailService userDetailService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String authHeader = request.getHeader("Authorization");
		// 解析Token的值，并根据解析结果查询用户信息，存入安全框架的上下文中
		if (authHeader != null && authHeader.startsWith("Bearer ")){
			String authToken = authHeader.substring("Bearer ".length());
			String userName = JwtTokenUtil.parseToken(authToken, "_secret");
			if (userName != null && SecurityContextHolder.getContext().getAuthentication() == null){
				UserDetails userDetails = userDetailService.loadUserByUsername(userName);
				if (userDetails != null){
					UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
					authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
					SecurityContextHolder.getContext().setAuthentication(authenticationToken);
				}
			}
		}
		filterChain.doFilter(request, response);
	}
}
